from django.template import Context, loader
from django.http import HttpResponse, HttpResponseNotFound
from django.utils import simplejson

import listing

def index(request, format):
    all_stories = listing.allstories()
    
    if format =='json':
        response = simplejson.dumps(all_stories, ensure_ascii=False,)
        mime = 'application/json'
    elif format == 'xml':
        t = loader.get_template('stories.xml')
        c = Context({
            'all_stories': all_stories,
            'many_stories': True,
        })
        response = t.render(c)
        mime = 'application/xml'
    else:
        return HttpResponseNotFound('404 Not Found')
    
    return HttpResponse(response, mimetype=mime)

def detail_story(request, story_id, format):
    story = listing.one_story(story_id)
       
    if not story:
        return HttpResponseNotFound('404 Story ID Not Found')
    
    if format =='json':
        response = simplejson.dumps(story, ensure_ascii=False,)
        mime = 'application/json'
    elif format == 'xml':
        t = loader.get_template('stories.xml')
        c = Context({
            'all_stories': story,
            'many_stories': False,
        })
        response = t.render(c)
        mime = 'application/xml'
    else:
        return HttpResponseNotFound('404 Not Found')
    
    return HttpResponse(response, mimetype=mime)